package top.linyuxb.lycloud.admin.web.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter;
import top.linyuxb.lycloud.admin.entity.LyConfEnvEntity;
import top.linyuxb.lycloud.admin.repository.LyConfEnvRepository;
import top.linyuxb.lycloud.admin.utils.CookieUtil;

import java.util.List;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/7/29 14:43
 * @Desc: 环境设置
 */
@Component
public class EnvInterceptor extends WebRequestHandlerInterceptorAdapter {

    public static final String CURRENT_ENV = "LY_CLOUD_CURRENT_ENV";

    @Resource
    private LyConfEnvRepository lyConfEnvRepository;

    public EnvInterceptor(WebRequestInterceptor requestInterceptor) {
        super(requestInterceptor);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // env list
        List<LyConfEnvEntity> envList = lyConfEnvRepository.findAll();
        if (CollectionUtil.isEmpty(envList)) {
            throw new RuntimeException("系统异常，获取Env数据失败");
        }

        // current env
        String currentEnv = envList.get(0).getEnv();
        String currentEnvCookie = CookieUtil.getValue(request, CURRENT_ENV);
        if (currentEnvCookie != null && !currentEnvCookie.trim().isEmpty()) {
            for (LyConfEnvEntity envItem : envList) {
                if (currentEnvCookie.equals(envItem.getEnv())) {
                    currentEnv = envItem.getEnv();
                }
            }
        }

        request.setAttribute("envList", envList);
        request.setAttribute(CURRENT_ENV, currentEnv);

        return super.preHandle(request, response, handler);
    }

}
